'use strict';
module.exports = {
	/**
	 * 新增记账
	 * @url client/accounting/record/kh/addKeepingData 前端调用的url参数地址
	 * data 请求参数
	 * @param {String} params1  参数1
	 */
	main: async (event) => {
		let { data = {}, userInfo, util, filterResponse, originalParam } = event;
		let { customUtil, uniID, config, pubFun, vk, db, _, $ } = util;
		let { uid, keepingData } = data;
		let res = { code: 0, msg: "新增成功" };
		// 业务逻辑开始-----------------------------------------------------------
		if(keepingData == null ){
			return { code : 1001, msg : '参数错误' };
		}
		
		let {isExpenses,icon,date,amount,remarks,books} = keepingData;
		if(pubFun.isEmpty(icon) || pubFun.isEmpty(date) || pubFun.isEmpty(amount) || pubFun.isEmpty(books)){
			return { code : 1001, msg : '参数错误' };
		}

		const _amount = Math.trunc(amount * 100)
		const paramUtil = vk.require("service/client/accountbook/util/paramUtil");
		let paramData = await paramUtil.initBaseInsertParam({uid,isExpenses,icon:icon.icon,iconName:icon.name,date:pubFun.formatTimestamp(date),time:date,amount:_amount,remarks });
		
		// 开启事务
		const transaction = await vk.baseDao.startTransaction();
		try {
			// 新增记账数据
			const dataId = await vk.daoCenter.bookKeepingDataDao.add({
				db: transaction,
				dataJson: paramData
			});
			if (dataId == null) {
				throw new Error("新增账本失败");
			}
			// 新增关联关系
			for(const book of books) {
				const _data = await paramUtil.initBaseInsertParam({bookId:book._id,dataId});
				const relationId = await vk.daoCenter.bookRelationDataDao.add({
					db: transaction,
					dataJson: _data
				});
				if (relationId == null) {
					throw new Error("新增关联关系失败");
				}
				
				// 更新账本数据
				book.totalCount = book.totalCount + 1
				if(isExpenses === "true") {
					book.totalEcpenditure = book.totalEcpenditure + _amount
				}
				else {
					book.totalRevenue = book.totalRevenue + _amount
				}
				book.surplus = book.totalRevenue + book.totalEcpenditure
				
				// 更新
				const _bookData = await paramUtil.dealUpdateParam(book);
				let row = await vk.baseDao.update({
					db: transaction, // 本次数据库语句带上事务对象（重要，必须带上）
					dbName:"db-account-book",
					whereJson: {
						_id: _.eq(_bookData._id)
					},
					dataJson: _bookData
				 });
			}
			
			// 提交事务
			await transaction.commit();
		} catch (err) {
			// 事务回滚
			await vk.baseDao.rollbackTransaction({db: transaction,err});
			console.error(`transaction error`, err)
		    return {
		      code: -1,
		      msg: "数据库写入异常,事务已回滚",
		      err: {
		        message: err.message,
		        stack: err.stack
		      },
			}
		}


		// 业务逻辑结束-----------------------------------------------------------
		return res;
	}
}